"""
 -*- coding: utf-8-*-
 @File: search_ceshiren.py
 @Author: chen
 @time: 2023/09/10/ 12:57
"""
import time

import allure
from selenium import webdriver
from selenium.webdriver.common.by import By


class SearchCeshiren:

    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)
        self.driver.get("https://ceshiren.com/")

    def teardown_class(self):
        self.driver.quit()

    def teardown_method(self):
        time.sleep(2)

    def get_screenshot(self):
        timestamp = int(time.time())
        picture_path = f"../screenshot/screenshot_{timestamp}.PNG"
        self.driver.save_screenshot(picture_path)
        allure.attach.file(picture_path, name="pictures", attachment_type=allure.attachment_type.PNG)

    def save_page_source(self):
        timestamp = int(time.time())
        page_source_path = f"../page_source/page_source_{timestamp}.html"
        with open(page_source_path, 'w', encoding="utf-8") as f:
            f.write(self.driver.page_source)
        # 如果想要页面效果可以使用HTML，如果想要看源码可以使用TEXT
        allure.attach.file(page_source_path, name="page_source", attachment_type=allure.attachment_type.HTML)

    def search(self, keyword):
        self.driver.find_element(By.CSS_SELECTOR, '.fa.d-icon.d-icon-search.svg-icon.svg-node').click()
        self.driver.find_element(By.CSS_SELECTOR, '.fa.d-icon.d-icon-sliders-h.svg-icon.svg-node').click()
        self.driver.find_element(By.XPATH, '//*[@aria-label="输入搜索关键字"]').send_keys(keyword)
        self.driver.find_element(By.XPATH, '//span[text()="搜索"]').click()
        ele = self.driver.find_elements(By.CSS_SELECTOR, '.topic-title')
        self.get_screenshot()
        self.save_page_source()
        # self.driver.quit()
        return ele



if __name__ == '__main__':
    c0 = SearchCeshiren()
    c0.search("selenium")
